<template>
  <div class="line-status-tv-board-page-wrapper">

    <div class="wrap-header">
      <div class="wrap-left">
        <div v-if="companyName==='彩霆电子'">
          <img class='img-logo'  src="@/common/images/icon-logo-caitingdianzi.jpg"/>
        </div>
<!--        <div v-else-if="companyName==='郑州市装联电子有限公司'">-->
        <div class="t-company-name one-line" style="display: flex;align-items: center" v-else-if="companyName==='郑州市装联电子有限公司'">
          <img class='img-logo-with'  src="@/common/images/icon-logo-zhuangliandianzi.jpg" style="margin-right: 1.5vw"/>
          {{companyName}}
        </div>
        <div class="t-company-name one-line" v-else>
          {{companyName}}
        </div>
      </div>
      <div v-if="false">
        <tv-clock></tv-clock>
      </div>

      <div class="wrap-right">
        <div class="triangle-topleft"></div>
        <div class="t-title one-line">
          {{$getTextByLangKey('SMT电子看板')}}・{{chanxian}}・{{shiftType}}
        </div>
      </div>

    </div>

    <div class="wrap-content">
      <div class="chart-wrap-row">

        <div class="chart-item chart-plan">

          <div class="chart-title">生产信息</div>

          <div class="plan-item">
            <img class='img-plan'  src="@/common/images/icon-plan-1.png"/>
            <span class="t-plan-job">机型</span>
            <span class="t-plan-name">{{nowProduce.machineType}}</span>
          </div>
          <div class="plan-item">
            <img class='img-plan'  src="@/common/images/icon-plan-1.png"/>
            <span class="t-plan-job">工单号</span>
            <span class="t-plan-name">{{nowProduce.workOrder}}</span>
          </div>
          <div class="plan-item">
            <img class='img-plan'  src="@/common/images/icon-plan-1.png"/>
            <span class="t-plan-job">程序名称</span>
            <span class="t-plan-name">{{nowProduce.programName}}</span>
          </div>
          <div class="plan-item">
            <img class='img-plan'  src="@/common/images/icon-plan-1.png"/>
            <span class="t-plan-job">计划数量</span>
            <span class="t-plan-name">{{nowProduce.plannedQuantity}}</span>
          </div>
          <div class="plan-item">
            <img class='img-plan'  src="@/common/images/icon-plan-1.png"/>
            <span class="t-plan-job">已生产数</span>
            <span class="t-plan-name">{{nowProduce.hasProducedQuantity}}</span>
          </div>
          <div class="plan-item">
            <img class='img-plan'  src="@/common/images/icon-plan-1.png"/>
            <span class="t-plan-job">开始时间</span>
            <span class="t-plan-name">{{nowProduce.startTime?nowProduce.startTime.substring(5,nowProduce.startTime.length):''}}</span>
          </div>
          <div class="plan-item">
            <img class='img-plan'  src="@/common/images/icon-plan-1.png"/>
            <span class="t-plan-job">贴装时间</span>
            <span class="t-plan-name">{{nowProduce.duration}}</span>
          </div>

        </div>


        <div class="chart-item chart-item-width-33 chart-graph-table-3" >
          <div class="chart-title"></div>
          <graphTable3 ref="graphTable3"></graphTable3>
        </div>
      </div>

      <div class="wrap-content-bottom">
        <!--        饼图-->
        <div class="chart-wrap-row" style="flex: 1">

          <div class="chart-inner-row">
            <div class="chart-item chart-pie chart-pie-1 ">
              <div class="chart-title"></div>
              <div style="width: 100%;height: 100%;">
                <pie1 ref="pie1"></pie1>
              </div>
            </div>

            <div class="chart-item chart-graph-1">
              <div class="chart-title">生产计划</div>
              <graphTable2 ref="graphTable2"></graphTable2>
            </div>
          </div>

          <div class="chart-item chart-item-width-33 chart-pie chart-person-3">
            <div style="width: 100%;height: 100%;" class="inner-wrap">
              <div class="chart-title">产线负责人员</div>

              <div class="person-content">
                <div class="person-item">
                  <img class='img-person' v-if="shiftType === '白班' || shiftType === 'Day shift'" :src="nowProduce.engineerImg+'&t='+new Date().getTime()"/>
                  <img class='img-person' v-else :src="nowProduce.nightEngineerImg+'&t='+new Date().getTime()" mode="aspectFill"/>
                  <span class="t-person-job">工程部：<span class="t-person-name" v-if="shiftType === '白班' || shiftType === 'Day shift'">{{nowProduce.engineer}}</span>
                  <span class="t-person-name" v-else>{{nowProduce.nightEngineer}}</span></span>

                </div>

                <div class="person-item">
                  <img class='img-person' v-if="shiftType === '白班' || shiftType === 'Day shift'" :src="nowProduce.operatorImg+'&t='+new Date().getTime()"/>
                  <img class='img-person' v-else :src="nowProduce.nightOperatorImg+'&t='+new Date().getTime()"/>
                  <span class="t-person-job">生产部：<span class="t-person-name" v-if="shiftType === '白班' || shiftType === 'Day shift'">{{nowProduce.operator}}</span>
                  <span class="t-person-name" v-else>{{nowProduce.nightOperator}}</span></span>

                </div>

                <div class="person-item">
                  <img class='img-person' v-if="shiftType === '白班' || shiftType === 'Day shift'" :src="nowProduce.qcImg+'&t='+new Date().getTime()"/>
                  <img class='img-person' v-else :src="nowProduce.nightQcImg+'&t='+new Date().getTime()"/>
                  <span class="t-person-job">品质部：<span class="t-person-name" v-if="shiftType === '白班' || shiftType === 'Day shift'">{{nowProduce.qc}}</span>
                  <span class="t-person-name" v-else>{{nowProduce.nightQc}}</span></span>

                </div>
              </div>

            </div>
          </div>


        </div>


        <div class="chart-wrap-row" style="flex: 1">
          <div class="chart-item chart-graph-1">
            <div class="chart-title">产量分析图</div>
            <div style="width: 100%;height: 100%;">
              <bar1 ref="bar1"></bar1>
            </div>
          </div>
          <div class="chart-item chart-graph-1">
            <div class="chart-title">换料记录</div>
            <graphTable1 ref="graphTable1"></graphTable1>
          </div>
        </div>
      </div>
    </div>

    <user-check></user-check>


    <el-dialog
      title="警告"
      :visible.sync="isInternetErrorDialogVisible"
      width="30%"
      top="35vh"
      :close-on-click-modal="false"
      >

      <span class="content-text">
         网络已断开或服务器关闭！
      </span>
      <span class="content-text">
        请检查网络和服务器后退出再登录！
      </span>

    </el-dialog>
  </div>


</template>

<script>



  import request from '@/common/js/request'
  import util from '@/common/js/util'
  import tvClock from '@/base/TVClock.vue'
  import usercheck from '@/base/usercheck.vue'
  import pie1 from '@/base/pie1.vue'
  import bar1 from '@/base/bar1.vue'
  import graphTable1 from '@/base/graphTable1.vue'
  import graphTable2 from '@/base/graphTable2.vue'
  import graphTable3 from '@/base/graphTable3.vue'



  export default {
    components: {
      'tv-clock': tvClock,
      'user-check': usercheck,
      'pie1': pie1,
      'bar1': bar1,
      'graphTable1': graphTable1,
      'graphTable2': graphTable2,
      'graphTable3': graphTable3,
    },

    data() {
      return {
        isInternetErrorDialogVisible:false,
        companyName:'',
        showCompanyName:true,
        chanxian:'',
        nowProduce:{},
        waitProduce:{},
        currentHourProduct:{},
        shiftType:'',
        producingHours:[],
        scantableData:[],
        waitTableData:[],
        pieTableData:[],
        requestCount:0,
        requestErrorStartTime:0,//用于统计是否网络异常
        autoRequestTimer:null,
      }
    },

    watch: {
      // 如果路由有变化，会再次执行该方法
      '$route': 'fetchData'
    },
    created: function () {
      this.chanxian = this.$route.query.chanxian
      // this.showCompanyName = this.$route.query.showCompanyName
      this.fetchCompanyName()

      if(this.chanxian){
        this.fetchLineStatus()
        this.fetchScanList(this.chanxian)
        this.startAutoRequestTimer()
      }


    },

    mounted() {

    },

    methods: {

      startAutoRequestTimer(){
        this.autoRequestTimer = setInterval(() => {
          if (this.requestCount === 0) {
            this.fetchLineStatus()
            this.fetchScanList(this.chanxian)
          } else {
          }
        }, 3000)
      },
      stopAutoRequestTimer(){
        clearTimeout(this.autoRequestTimer)
      },

      updateBroadView(){

        this.updatePieChartView({nowProduce:this.nowProduce,currentHourProduct:this.currentHourProduct})
        this.updateBarChartView({producingHours:this.producingHours})
        this.updateGraphTableView({tableData:this.scantableData,waitTableData:this.waitTableData})
      },

      updatePieChartView({nowProduce,currentHourProduct}){

        const plannedQuantity = nowProduce.plannedQuantity
        const hasProducedQuantity = nowProduce.hasProducedQuantity
        const noProducedQuantity = plannedQuantity?(plannedQuantity - hasProducedQuantity):0
        const rate1 = plannedQuantity?((hasProducedQuantity/plannedQuantity)*100).toFixed(2)+'%':'0%'

        // 饼图2
        const plannedPcbaSpots = nowProduce.pcbaSpots * currentHourProduct.designedOutput
        const hasProducedPcbaSpots =  currentHourProduct.spots
        const noProducedPcbaSpots =  plannedPcbaSpots&&plannedPcbaSpots>hasProducedPcbaSpots?plannedPcbaSpots-hasProducedPcbaSpots:0
        const rate2 = plannedPcbaSpots?((hasProducedPcbaSpots/plannedPcbaSpots)*100).toFixed(2)+'%':'0%'
        // 饼图3
        const designedOutput = currentHourProduct.designedOutput?currentHourProduct.designedOutput:0
        const realOutput = currentHourProduct.realOutput?currentHourProduct.realOutput:0
        const noOutput = designedOutput&&designedOutput>realOutput?designedOutput-realOutput:0
        const rate3 = ((realOutput/designedOutput)*100).toFixed(2)+'%'


        const pieTableData = []
        pieTableData.push({index:'当前1小时点数完成率: ',rate:rate2})
        pieTableData.push({index:'当前1小时效率: ',rate:rate2})
        pieTableData.push({index:'计划每小时生产数量: ',rate:designedOutput})
        pieTableData.push({index:'工艺: ',rate:nowProduce.technology})

        const pie1Config = {
          color: [
            '#96BFFF',
            '#fb7293',
          ],
          title: {
            text: `数量完成率 ${rate1}`,
            left: 'center'
          },
          data:[
            { value: hasProducedQuantity, name: '已产数量' },
            { value: noProducedQuantity, name: '待产数量' },
          ]
        }


        const pie2Config = {
          color: [
            '#8378EA',
            '#E062AE',
          ],
          title: {
            text: `当前一小时PCBA点数完成率 ${rate2}`,
            left: 'center'
          },
          data:[
            { value: hasProducedPcbaSpots, name: '已焊点数' },
            { value: noProducedPcbaSpots, name: '未焊点数' },
          ]
        }

        const pie3Config = {
          color: [
            '#73a373',
            '#FFDB5C',
          ],
          title: {
            text: `当前一小时效率 ${rate3}`,
            left: 'center'
          },
          data:[
            { value: realOutput, name: '已产数量' },
            { value: noOutput, name: '待产数量' },
          ]
        }

        this.$nextTick(()=>{
          this.$refs.pie1.updateEcharts(pie1Config)
          // this.$refs.pie2.updateEcharts(pie2Config)
          // this.$refs.pie3.updateEcharts(pie3Config)
          this.$refs.graphTable3.updateEcharts(pieTableData)
        })
      },

      updateBarChartView({producingHours}){
        const barProducingHours = this.makeBarProducingHours(producingHours)

        const firstHourDesignedOutput = producingHours&&producingHours.length>=1&&producingHours[0].designedOutput?producingHours[0].designedOutput:100


        const bar1Config = {
          color:['#91ca8c'],
          xData:barProducingHours.xData,
          yData:barProducingHours.yData,
          yMax:firstHourDesignedOutput
        }

        this.$nextTick(()=>{
          this.$refs.bar1.updateEcharts(bar1Config)
        })
      },

      updateGraphTableView({tableData,waitTableData}){
        this.$nextTick(()=>{
          this.$refs.graphTable1.updateEcharts(tableData)
          this.$refs.graphTable2.updateEcharts(waitTableData)

        })
      },



      fetchCompanyName(){
        request.requestGetCompanyName(res=>{
          this.companyName = res.data.data
          // if(this.companyName === '彩霆电子'||this.companyName === '郑州市装联电子有限公司'){
          //   this.showCompanyName = false
          // }
        })
      },
      fetchLineStatus(){

        this.requestCount ++
        request.requestLineStatus(this.chanxian, res => {
          this.requestCount --
          this.hideRequestErrorStartTime()
          if (res.data.data.nowProduce === null) {
            this.nowProduce = {}
          } else {
            let nowProduce = res.data.data.nowProduce
            nowProduce.startTime = this.getTimeToDate(nowProduce.startTime)
            nowProduce.finalTime = this.getTimeToDate(nowProduce.finalTime)
            nowProduce.estimateFinishTime = this.getTimeToDate(nowProduce.estimateFinishTime)
            nowProduce.estimateStartTime = this.getTimeToDate(nowProduce.estimateStartTime)
            this.nowProduce = nowProduce
          }

          if (res.data.data.waitProduce === null) {
            this.waitProduce = {}
          } else {
            let waitProduce = res.data.data.waitProduce
            waitProduce.startTime = this.getTimeToDate(waitProduce.startTime)
            waitProduce.finalTime = this.getTimeToDate(waitProduce.finalTime)
            waitProduce.estimateFinishTime = this.getTimeToDate(waitProduce.estimateFinishTime)
            waitProduce.estimateStartTime = this.getTimeToDate(waitProduce.estimateStartTime)
            this.waitProduce = waitProduce
          }
          this.shiftType = res.data.data.shiftType
          this.producingHours = res.data.data.producingHours

          this.currentHourProduct = this.makeCurrentHourProduct(res.data.data.producingHours)
          const waitTableData = []
          const pieTableData = []

          if(res.data.data.nowProduce){
            let temp_nowProduce = res.data.data.nowProduce
            waitTableData.push({index:'当前',machineType:temp_nowProduce.machineType,plannedQuantity:temp_nowProduce.plannedQuantity,startTime: this.getTimeToDate(temp_nowProduce.startTime)})
          }

          if(res.data.data.waitProduce){
            let temp_waitProduce = res.data.data.waitProduce
            waitTableData.push({index:'等待1',machineType:temp_waitProduce.machineType,plannedQuantity:temp_waitProduce.plannedQuantity,startTime: temp_waitProduce.startTime})
            waitTableData.push({index:'等待2',machineType:temp_waitProduce.machineType2,plannedQuantity:temp_waitProduce.plannedQuantity2,startTime: temp_waitProduce.startTime2})
            waitTableData.push({index:'等待3',machineType:temp_waitProduce.machineType3,plannedQuantity:temp_waitProduce.plannedQuantity3,startTime: temp_waitProduce.startTime3})
          }

          this.pieTableData = pieTableData

          this.waitTableData = waitTableData

          this.updateBroadView()

        }, res => {
          this.requestCount --
          this.showRequestErrorStartTime()
        })
      },

      hideRequestErrorStartTime(){
        this.requestErrorStartTime = 0
        this.isInternetErrorDialogVisible = false
      },

      showRequestErrorStartTime(){
        if(!this.requestErrorStartTime){
          this.requestErrorStartTime = new Date().getTime()
          return
        }

        const currentTime = new Date().getTime()
        if(currentTime - this.requestErrorStartTime > 10*1000){
          this.isInternetErrorDialogVisible = true
        }

      },


      fetchScanList(lineName){
        this.requestCount ++
        request.requestScanList(lineName,'', 1, 100, '', '', '', '',res=>{
          this.requestCount --
          this.hideRequestErrorStartTime()

          const resdata = res.data.data || {}
          // 设备，站位，扫描时间，用户，规格，正确编码1，扫入编码，换料数量
          this.scantableData = resdata.list.map(x=>{
            return {
              ...x,scanTime:this.getTimeToDate(x.scanTime)
            }
          }).slice(0,4)



          // this.waitTableData =

          // this.scantableData = [...this.scantableData,...this.scantableData]
          this.updateBroadView()
        },err=>{
          this.requestCount --
          this.showRequestErrorStartTime()
        })
      },


      makeCurrentHourProduct:function(producingHours){
        const hour = new Date().getHours()

        const currentTime = hour>9?`${hour}:00`:`0${hour}:00`

        const currentTimeIndex = producingHours.findIndex(x=>{
          return x.hourRange.startsWith(currentTime)
        })

        if(currentTimeIndex>=0){
          return producingHours[currentTimeIndex]
        }
        return {}

      },


      setEnough12Time(barProducingHours){

        if(barProducingHours.length === 0){
          return [
            {
              "hourRange": "20:00",
              "realOutput": 0
            },
            {
              "hourRange": "21:00",
              "realOutput": 0
            },
            {
              "hourRange": "22:00",
              "realOutput": 0
            },
            {
              "hourRange": "23:00",
              "realOutput": 0
            },
            {
              "hourRange": "00:00",
              "realOutput": 0
            },
            {
              "hourRange": "01:00",
              "realOutput": 0
            },
            {
              "hourRange": "02:00",
              "realOutput": 0
            },
            {
              "hourRange": "03:00",
              "realOutput": 0
            },
            {
              "hourRange": "04:00",
              "realOutput": 0
            },
            {
              "hourRange": "05:00",
              "realOutput": 0
            },
            {
              "hourRange": "06:00",
              "realOutput": 0
            },
            {
              "hourRange": "07:00",
              "realOutput": 0
            }
          ]
        }


        const new12EnoughTime = []
        const startTime = parseInt(barProducingHours[0].hourRange.split(':')[0])

        for(let i =0;i<=11;i++){
          const item = barProducingHours[i]
          if(item){
            new12EnoughTime.push(item)
          }else{
            const newTime = (startTime+i)%24>0?(startTime+i)%24:(startTime+i)
            const newTimeStr = newTime>10?newTime+'':'0'+newTime
            const newItem = {
              "hourRange": newTimeStr+':00',
              "realOutput": 0
            }
            new12EnoughTime.push(newItem)
          }

        }
        return new12EnoughTime

      },

      makeBarProducingHours(producingHours){
        let barProducingHours = producingHours.map((x)=>{
          return {hourRange:x.hourRange.substring(0,5),realOutput:x.realOutput}
        })

        //补齐十二个
        barProducingHours = this.setEnough12Time(barProducingHours)

        const xData = barProducingHours.map((x)=>{
          return x.hourRange
        })

        const yData = barProducingHours.map((x)=>{
          return x.realOutput
        })

        return {xData,yData}
      },

      getTimeToDate: function (time) {

        if (time != null) {
          var date = new Date(time).format("yyyy/MM/dd hh:mm")
          return date
        }
        return ''
      },
    },

    destroyed: function () {
      this.stopAutoRequestTimer()
    },




  }
</script>

<style lang="stylus">


  .line-status-tv-board-page-wrapper{
    .el-dialog{

      .el-dialog__body{
        padding 10px 20px 30px 20px
        .content-text{
          display:inline-block;
          font-size: 18px;
          line-height: 20px;
          color: #F56C6C;
          padding-bottom: 1.0vh
        }
      }
    }
  }

  .one-line{
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
  }

  .triangle-topleft {
    border: 4vh solid rgb(43,128,211);
    height: 0;
    width: 0;
    border-right-color: transparent;
    border-bottom-color: transparent;
  }

    .chart-wrap-row{
      display flex

      .chart-inner-row{
        display flex
        flex 1
        width 66vw
      }
    }
    .chart-item{
      border 1px solid #2168b2
      /*border 1px solid #4A90E2*/
      /*border 1px solid #F5F5F5*/
      border-radius 4px
      margin 6px
      flex 1
      position relative
      padding 2.5vw 1vw 1.5vw 1vw
      color white

      &.chart-item-width-33{
        width 33vw
        flex-grow 0
        flex-shrink 0
        flex none
      }

      &.chart-graph-table-3{
        padding-top 1.2vw
      }

      &.chart-pie{
        padding 1.5vw 1vw 0.5vw 1vw

      }
      .chart-title{
        position absolute
        top 0.5vw
        right 1vw
        font-size 1.6vh
      }

      &.chart-person-3{

        .inner-wrap{
          display flex
        }
        .person-content{
          display flex
          flex 1
          padding-top 1.5vw
          .person-item{
            display flex
            flex-direction column
            align-items center
            flex 1
            height 100%
            .img-person{
              width 92%;
              border-radius 4px;
              height 82%
              flex-grow 0
              flex-shrink 0
              object-fit contain
              /*height 5vh;*/
            }
            .t-person-job{
              margin-top 1.8vh
            }
            .t-person-name{
              margin-top 0.8vh
            }
          }
        }
      }
    }

    .chart-person{
      display flex

      .person-item{
        display flex
        flex-direction column
        align-items center
        margin-right 10px
        flex 1
        flex-shrink 0

        .img-person{
          width 5vh;
          height 5vh;
        }
        .t-person-job{
          margin-top 0.5vh
        }
        .t-person-job,.t-person-name{
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          max-width 10vh
        }
      }
    }
    .chart-plan{
      display flex
      flex 1

      .plan-item{
        display flex
        flex-direction column
        align-items center
        margin-right 10px
        flex 1
        flex-shrink 0

        .img-plan{
          width 5vh;
          height 5vh;
        }
        .t-plan-job{
          margin-top 0.5vh
        }
        .t-plan-job,.t-plan-name{
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          max-width 10vh
        }
      }
    }
  .line-status-tv-board-page-wrapper {
    width 98.4vw
    height calc(100vh - 0.8vw)
    font-family: "Noto Sans SC";
    background-color rgb(43,128,211);
    padding 0 0.8vw 0.8vw 0.8vw
    display flex
    flex-direction column
    font-size: 1.4vh;
    line-height: 1.8vh;
    .wrap-header{
      height 10.8vh;
      display flex
      flex-direction row
      align-items center
      padding-left 1.5vw
      font-size 5vh
      .wrap-left{
        flex 1
        .t-company-name{
          color white
          font-size 4vh
          line-height 5.2vh
          margin-right 4vw
        }

        .img-logo{
          height 8vh
        }
        .img-logo-with{
          height 6vh
        }
      }

      .wrap-right{
        background-color #F5F5F5
        display flex
        width 60%
        .t-title{
          flex 1
          padding 0 5vw
          display flex
          flex-direction row
          align-items center
          justify-content center
          font-size 4vh
          line-height 5.2vh
        }
      }

    }

    .wrap-content{
      /*background-color #2B80D3*/
      /*background-color white*/
      flex 1
      display flex
      flex-direction column
      padding 1px
      .wrap-content-bottom{
        flex 1
        display flex
        flex-direction column
      }
    }
  }


</style>


